<template>
  <div class="editor">
    <tiny-editor
      api-key="izuqszdbzd4kyrez7fr6q94e6p97c135qdyoe9h1ems9p1sr"
      v-bind="$attrs"
      :init="init"
    ></tiny-editor>
  </div>
</template>

<script>
  import tinymce from 'tinymce/tinymce';
  import TinyEditor from '@tinymce/tinymce-vue';
  import 'tinymce/themes/silver';
  import 'tinymce/icons/default';

  import 'tinymce/plugins/preview';
  import 'tinymce/plugins/searchreplace';
  import 'tinymce/plugins/autolink';
  import 'tinymce/plugins/directionality';
  import 'tinymce/plugins/visualblocks';
  import 'tinymce/plugins/visualchars';
  import 'tinymce/plugins/fullscreen';
  import 'tinymce/plugins/image';
  import 'tinymce/plugins/link';
  import 'tinymce/plugins/media';
  import 'tinymce/plugins/template';
  import 'tinymce/plugins/code';
  import 'tinymce/plugins/codesample';
  import 'tinymce/plugins/table';
  import 'tinymce/plugins/charmap';
  import 'tinymce/plugins/hr';
  import 'tinymce/plugins/nonbreaking';
  import 'tinymce/plugins/insertdatetime';
  import 'tinymce/plugins/lists';
  import 'tinymce/plugins/wordcount';
  import 'tinymce/plugins/imagetools';
  import 'tinymce/plugins/textpattern';
  import 'tinymce/plugins/autosave';
  import 'tinymce/plugins/autoresize';

  export default {
    props: {
      cvIdPath: {
        default: '',
      },
    },
    components: {
      TinyEditor,
    },
    data() {
      return {
        editor: null,
        flag: true,
        init: {
          setup: (editor) => {
            this.editor = editor;
            this.setContent();
          },
          language_url: '/static/tinymce/langs/zh_CN.js', // 中文语言包路径
          language: 'zh_CN',
          skin_url: '/static/tinymce/skins/ui/oxide',
          min_height: 400,
          max_height: 700,
          toolbar_mode: 'wrap',
          forced_root_block: false,
          external_plugins: { powerpaste: '/static/tinymce/plugins/powerpaste/plugin.min.js' },
          //选择文本时的快捷栏
          quickbars_selection_toolbar:
            'bold italic underline forecolor backcolor | fontselect |fontsizeselect | formatselect | quicklink blockquote',
          //选中图片时的快捷栏
          quickbars_image_toolbar: 'alignleft aligncenter alignright quicklink |  imageoptions',
          plugins:
            'preview  searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr nonbreaking insertdatetime lists wordcount imagetools textpattern autosave  autoresize ',
          toolbar:
            'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link codesample | alignleft aligncenter alignright alignjustify outdent indent  formatpainter | \
    styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
    table image media charmap hr pagebreak insertdatetime | bdmap fullscreen preview',
          contextmenu: 'link image imagetools inserttable | cell row column deletetable | headings',
          content_style: 'p {margin: 0;}',
          content_css: '/static/tinymce/custom.css',
          fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
          powerpaste_word_import: 'propmt', // 参数可以是propmt, merge, clear，效果自行切换对比
          powerpaste_html_import: 'propmt', // propmt, merge, clear
          powerpaste_allow_local_images: true,
          paste_data_images: true,
          relative_urls: false,
          remove_script_host: false,
          font_formats:
            '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',
          branding: false,
          //此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
          //如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
          images_upload_handler: (blobInfo, success, failure, progress) => {
            const file = new File([blobInfo.blob()], blobInfo.filename());
            this.$UploadCore({
              isPublic: true,
              file,
              folder: `${['guide', this.cvIdPath].filter((p) => p).join('/')}`,
            })
              .then((res) => {
                success(res.url);
                // 如果是拖动上传的话，由于父组件无法更新上传之后的值，这里重新赋值
                this.$emit('input', this.editor.getContent());
                this.$message.success('图片添加成功!');
              })
              .catch((err) => {
                console.log(err);
                this.$message.error('图片上传失败');
              });
          },
        },
      };
    },
    watch: {
      $attrs() {
        if (this.flag) {
          this.editor.setContent(this.$attrs.value || '', { format: 'raw' });
        }
        this.flag = true;
      },
    },
    mounted() {
      tinymce.init({});
      this.setContent();
    },
    methods: {
      setContent() {
        setTimeout(() => {
          if (!this.editor || !this.editor.parser || !this.editor.parser.parse) {
            return this.setContent();
          }

          this.editor.setContent(this.$attrs.value || '', { format: 'raw' });
          this.editor.on('input execCommand paste redo undo', () => {
            this.flag = false;
            this.$emit('input', this.editor.getContent());
          });
        });
      },
    },
  };
</script>

<style lang="less"></style>
